import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView.vue'
import PublicActivitiesView from '../views/PublicActivitiesView.vue'
import PublicActivityDetailView from '../views/PublicActivityDetailView.vue'
import ActivityManagementView from '../views/ActivityManagementView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: PublicActivitiesView
  },
  {
    path: '/public-activities/:id',
    name: 'public-activity-detail',
    component: PublicActivityDetailView
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: ActivityManagementView,
    meta: { requiresAuth: true, requiresAdmin: true }
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  const isAdmin = localStorage.getItem('isAdmin') === 'true'

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isLoggedIn) {
      next('/login')
    } else {
      if (to.matched.some(record => record.meta.requiresAdmin)) {
        if (isAdmin) {
          next()
        } else {
          next('/login')  // 修改为跳转到登录页面
        }
      } else {
        next()
      }
    }
  } else {
    next()
  }
})

export default router
